package cn.yunbamboos.rest.service.apidoc.meta.schema;

import cn.hutool.core.util.ObjUtil;
import cn.yunbamboos.rest.service.apidoc.IMeta;
import cn.yunbamboos.rest.service.apidoc.meta.Schema;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

public class ArraySchema extends BaseSchema {

    private Schema items;

    public ArraySchema(String path) {
        super(path,"array");
    }

    @Override
    public JSONObject toJSON() {
        JSONObject json = new JSONObject();
        json.put("type", "array");
        if(ObjUtil.isNotNull(this.items)){
            json.put("items", items.toJSON());
        }
        return json;
    }

    @Override
    public void setItems(Schema items) {
        this.items = items;
    }

    @Override
    public void toExample(JSONObject example) {
        JSONArray array = new JSONArray();
        if(items != null){
            if(items instanceof DefaultSchema defaultSchema){
                JSONObject item = new JSONObject();
                defaultSchema.toExample(item);
                array.add(item.get(defaultSchema.getPath()));
            }
            if(items instanceof ObjectSchema objectSchema){
                JSONObject item = new JSONObject();
                objectSchema.toExample(item);
                array.add(item.getJSONObject(objectSchema.getPath()));
            }
        }
        example.put(path, array);
    }
}
